package de.uni_mannheim.informatik.ai.dame_ai.util;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;

import de.uni_mannheim.informatik.ai.dame_ai.main.application.GameSettings;
import de.uni_mannheim.informatik.ai.dame_ai.main.application.MainPlayer;


public class GameSettingsParser {
	private XmlCompiler compiler = new XmlCompiler();
	private XmlParser parser= new XmlParser();
	
	public String compileXml(XmlElement element){
		return compiler.compile(element);
	}
	public GameSettings getGameSettings(File dest){
		XmlElement root =this.getRoot(dest);
		return getGameSettings(root);
	}
	
	public XmlElement setGameSettings(GameSettings data){
		XmlElement gameSettings = new XmlElement("gameSettings");
		for(MainPlayer players : data.getPlayers()){
			XmlElement player = new XmlElement("player");
			player.addChild("name",players.getName());
			player.addChild("number",""+players.getNumber());
			player.addChild("human",""+players.isHuman());
			gameSettings.addChild(player);
		}
		gameSettings.addChild("language",""+data.getLanguage());
		gameSettings.addChild("isLoadGame",""+data.isLoadGame());
		gameSettings.addChild("isReplay",""+data.isReplay());
		gameSettings.addChild("file",""+data.getFilePath());
		gameSettings.addChild("finished",""+data.isFinished());
		return gameSettings;
	}
	public GameSettings getGameSettings(XmlElement root){
		GameSettings newData = new GameSettings();
		ArrayList<MainPlayer> players = new ArrayList<MainPlayer>();
		Collection<XmlElement> elements =root.getChildren();
		for(XmlElement element : elements){
			if(element.getTagName().equals("gameSettings")){
				Collection<XmlElement> childPlayers =element.getChildren();
				for(XmlElement child : childPlayers){
					if(child.getTagName().equals("player")){
						MainPlayer temp = new MainPlayer();
						temp.setName(child.getChild("name").getContent());
						temp.setHuman(Boolean.parseBoolean(child.getChild("human").getContent()));
						temp.setNumber(Integer.parseInt(child.getChild("number").getContent()));
						players.add(temp);
					}
				}
				newData.setPlayers(players.toArray(new MainPlayer[players.size()]));
				newData.setLanguage(Integer.parseInt(element.getChild("language").getContent()));
				newData.setLoadGame(Boolean.parseBoolean(element.getChild("isLoadGame").getContent()));
				newData.setReplay(Boolean.parseBoolean(element.getChild("isReplay").getContent()));
				newData.setFinished(Boolean.parseBoolean(element.getChild("finished").getContent()));
				newData.setFilePath(new File(element.getChild("file").getContent()));
				
			}
		}
		return newData;
		
		
	}
	public XmlElement getRoot(File destFile){
		String xmlFile = FileAccess.readFile(destFile);
		XmlElement root = null;
		try {
			root = parser.parse(xmlFile);
		} catch (InvalidXmlException e) {
			e.printStackTrace();
		}
		return root;
	}
}
